package com.szt.sy.controller.system.dict;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.szt.sy.anontation.Authority;
import com.szt.sy.anontation.AuthorityConfig;
import com.szt.sy.anontation.SysLog;
import com.szt.sy.common.AuthorityCommon;
import com.szt.sy.controller.base.AdminBaseController;
import com.szt.sy.entity.system.Dict;
import com.szt.sy.service.system.dict.DictService;
import com.szt.sy.util.date.DateUtil;
import com.szt.sy.util.excel.ObjectExcelView;
import com.szt.sy.vo.rep.base.RepBaseVO;
import com.szt.sy.vo.req.page.ReqPageVO;

/**
 * @author wwy
 *
 *         <p>
 *         说明：数据字典控制器<br/>
 *         创建时间：2018-01-15
 *         </p>
 */
@Controller
@AuthorityConfig(prefix = "/admin/dict/list")
@RequestMapping(value = "admin/dict")
public class DictController extends AdminBaseController {
	
	@Autowired
	private DictService dictService;
	
	/**
	 * 去列表页面
	 * 
	 */
	@Authority(name = AuthorityCommon.LIST)
	@GetMapping(value = "/list")
	public ModelAndView goPage(@RequestParam Map<String, Object> map) {
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("system/dict/dict_list");
		mv.addObject("queryParam", map);
		// 按钮权限
		
		return mv;
	}
	
	/**
	 * 列表数据
	 */
	@SysLog("查询数据字典列表数据")
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Authority(name = AuthorityCommon.LIST)
	@PostMapping(value = "/list")
	@ResponseBody
	public RepBaseVO list(ReqPageVO pageVO, @RequestParam Map<String, Object> map) {
		RepBaseVO repVO = new RepBaseVO<>();
		processParams(map);
		Page<Dict> page = processPage(pageVO);
		page = dictService.list(page, map);
		List<Dict> varList = page.getRecords();
		Map<String, Object> resultInfo = new HashMap<>(2);
		resultInfo.put("data", varList);
		resultInfo.put("total", page.getTotal());
		return repVO.setCommonSuccess().setData(resultInfo);
	}
	
	/**
	 * 去新增页面
	 */
	@Authority(name = AuthorityCommon.ADD)
	@GetMapping(value = "/add")
	public ModelAndView goAdd(@RequestParam Map<String, Object> map) {
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("system/dict/dict_edit");
		Dict entity = new Dict();
		entity.setTypeId(Long.parseLong(map.get("typeId").toString()));
		mv.addObject("msg", "add");
		mv.addObject("entity", entity);
		mv.addObject("pd", map);
		return mv;
	}
	
	/**
	 * 保存
	 */
	@SysLog("添加数据字典数据")
	@Authority(name = AuthorityCommon.ADD)
	@PostMapping(value = "/add")
	@ResponseBody
	public RepBaseVO save(Dict entity) {
		RepBaseVO repVO = new RepBaseVO();
		entity.setVersion(1L);
		entity.setCode(entity.getCode().toUpperCase().trim());
		entity.setAddDate(new Date());
		entity.setEditable(Dict.EDITABLE_TRUE);
		entity.setVisible(Dict.VISIBLE_TRUE);
		boolean codeExist = dictService.selectCount(
				new EntityWrapper<Dict>().eq("code", entity.getCode()).eq("typeId", entity.getTypeId())) >= 1;
		if (codeExist) {
			return repVO.setCommonFail().setMes("代码编码已存在");
		}
		dictService.insert(entity);
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 去修改页面
	 */
	@Authority(name = AuthorityCommon.EDIT)
	@GetMapping(value = "/edit")
	public ModelAndView goEdit(Long id) {
		ModelAndView mv = this.getModelAndView();
		Dict entity = dictService.selectById(id);
		mv.setViewName("system/dict/dict_edit");
		mv.addObject("msg", "edit");
		mv.addObject("entity", entity);
		return mv;
	}
	
	/**
	 * 修改
	 */
	@SysLog("修改数据字典数据")
	@Authority(name = AuthorityCommon.EDIT)
	@PostMapping(value = "/edit")
	@ResponseBody
	public RepBaseVO edit(Dict entity) {
		RepBaseVO repVO = new RepBaseVO<>();
		entity.setCode(entity.getCode().toUpperCase().trim());
		boolean codeExist = dictService.selectCount(new EntityWrapper<Dict>().eq("code", entity.getCode())
				.eq("typeId", entity.getTypeId()).ne("id", entity.getId())) >= 1;
		if (codeExist) {
			return repVO.setCommonFail().setMes("代码编码已存在");
		}
		dictService.updateById(entity);
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 删除
	 */
	@SysLog("删除数据字典数据")
	@Authority(name = AuthorityCommon.DELETE)
	@PostMapping(value = "/delete")
	@ResponseBody
	public RepBaseVO delete(Long id) {
		dictService.deleteById(id);
		return RepBaseVO.newIntance().setCommonSuccess();
	}
	
	/**
	 * 批量删除
	 */
	@SysLog("批量删除数据字典数据")
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Authority(name = AuthorityCommon.DELETE)
	@PostMapping(value = "/deleteAll")
	@ResponseBody
	public RepBaseVO deleteAll(String ids) {
		RepBaseVO repVO = new RepBaseVO<>();
		if (null != ids && !"".equals(ids)) {
			String[] idArray = ids.split(",");
			dictService.deleteBatchIds(Lists.newArrayList(idArray));
			
		}
		return repVO.setCommonSuccess();
	}
	
	@PostMapping("visible/change")
	@ResponseBody
	public RepBaseVO changeVisible(Long id) {
		RepBaseVO repVO = new RepBaseVO<>();
		Dict dict = dictService.selectById(id);
		if (dict == null) {
			return repVO.setCommonFail().setMes("数据不存在");
		}
		if (dict.getVisible().equals(Dict.VISIBLE_FALSE)) {
			dict.setVisible(Dict.VISIBLE_TRUE);
		} else {
			dict.setVisible(Dict.VISIBLE_FALSE);
		}
		dictService.updateById(dict);
		return repVO.setCommonSuccess();
	}
	
	/**
	 * 导出到excel
	 */
	@SysLog("导出数据字典excel")
	@Authority(name = AuthorityCommon.LIST)
	@PostMapping(value = "/excel")
	public ModelAndView exportExcel(@RequestParam Map<String, Object> map) {
		ModelAndView mv = new ModelAndView();
		processParams(map);
		Map<String, Object> dataMap = new HashMap<String, Object>(2);
		List<String> titles = new ArrayList<String>();
		titles.add("类型id");
		titles.add("名称");
		titles.add("代码编号");
		titles.add("能否编写,-1:不能修改,1-可以修改");
		titles.add("排序");
		titles.add("额外信息");
		titles.add("是否可见,-1:不可见,1-:可见");
		dataMap.put("titles", titles);
		List<Dict> varOList = dictService.listAll(map);
		List<Map<String, Object>> varList = new ArrayList<Map<String, Object>>();
		for (Dict entity : varOList) {
			Map<String, Object> vpd = new HashMap<String, Object>(30);
			vpd.put("var1", entity.getTypeId());
			vpd.put("var2", entity.getName());
			vpd.put("var3", entity.getCode());
			vpd.put("var4", entity.getEditable());
			vpd.put("var5", entity.getSort());
			vpd.put("var6", entity.getExtra());
			vpd.put("var7", entity.getVisible());
			varList.add(vpd);
		}
		
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv, dataMap);
		return mv;
	}
	
	/***
	 * 处理输入参数
	 * 
	 * @param map
	 */
	private void processParams(Map<String, Object> map) {
		String sStartDate = (String) map.get("lastStart");
		String sEndDate = (String) map.get("lastEnd");
		if (StringUtils.isBlank(sStartDate)) {
			map.put("lastStart", null);
		} else {
			map.put("lastStart", DateUtil.getStartTimeOfDate(sStartDate));
		}
		if (StringUtils.isBlank(sEndDate)) {
			map.put("lastEnd", null);
		} else {
			map.put("lastEnd", DateUtil.getEndTimeOfDate(sEndDate));
		}
	}
	
	/***
	 * 处理分页参数
	 * 
	 * @param pageVO
	 * @return
	 */
	private Page<Dict> processPage(ReqPageVO pageVO) {
		Page<Dict> page = new Page<>(pageVO.getCurrent(), pageVO.getSize());
		if (StringUtils.isNotBlank(pageVO.getSortColumn())) {
			page.setOrderByField(pageVO.getSortColumn());
			if ("ASC".equals(pageVO.getSortDirection())) {
				page.setAsc(true);
			} else {
				page.setAsc(false);
			}
		} else {
			page.setOrderByField("addDate");
			page.setAsc(false);
		}
		return page;
	}
	
}
